package com.core.family.admin.service.Impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.core.common.gen.BaseQuery;
import com.core.common.gen.BaseServiceImpl;
import com.core.common.gen.PageQuery;
import com.core.family.admin.Interceptor.UserUtil;
import com.core.family.admin.domain.dto.GroupDto;
import com.core.family.admin.domain.dto.UserGp;
import com.core.family.admin.domain.po.SysGroup;
import com.core.family.admin.domain.po.SysRoleG;
import com.core.family.admin.mapper.SysGroupMapper;
import com.core.family.admin.service.SysGroupService;
import com.core.family.admin.service.SysRoleGService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author honglei
 * @version 1.0
 * @time: 2022-6-10 11:46:34
 * @Description 服务实现层
 */
@Service
public class SysGroupServiceImpl extends BaseServiceImpl<SysGroupMapper, SysGroup> implements SysGroupService {

    @Autowired
    SysRoleGService sysRoleGService;


    /***
     * 分页返回 用户组
     * @param sysGroup
     * @param pageQuery
     * @return
     */
    @Override
    public IPage<SysGroup> selectPage(SysGroup sysGroup, PageQuery<BaseQuery> pageQuery) {
        IPage<SysGroup> page = super.selectPage(sysGroup, pageQuery);

        Set<Integer> setGroupId = new HashSet<>();
        List<GroupDto> dtoList = new ArrayList<>();
        for (SysGroup group : page.getRecords()) {
            GroupDto groupDto = new GroupDto();
            BeanUtils.copyProperties(group, groupDto);
            dtoList.add(groupDto);
            setGroupId.add(group.getId());
        }
//        根据分组集合查询分组具有的角色集合
        List<SysRoleG> sysRoleGS = sysRoleGService.listByGroupIds(UserUtil.getOrgId(), setGroupId);
        Map<Integer, List<SysRoleG>> listMap = sysRoleGS.stream().collect(Collectors.groupingBy(SysRoleG::getGid));

        for (GroupDto groupDto : dtoList) {
            if (listMap.containsKey(groupDto.getId())) {
                groupDto.setRoles(listMap.get(groupDto.getId()));
            }
        }

        IPage iPage = new Page();
        BeanUtils.copyProperties(page, iPage);
        iPage.setRecords(dtoList);
        return iPage;
    }
}

